#include <windows.h>		// Header File For Windows

#include "render.h"
#include "struct.h"
#include "system.h"

HWND		g_hWnd;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc
int g_bTrackMouse;

extern UFOAPP_INFO g_appInfo;

#if(_WIN32_WINNT < 0x0400)
typedef struct tagTRACKMOUSEEVENT {
	DWORD cbSize;
	DWORD dwFlags;
	HWND  hwndTrack;
	DWORD dwHoverTime;
} TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;

WINUSERAPI BOOL WINAPI TrackMouseEvent(LPTRACKMOUSEEVENT lpEventTrack);
#define GET_WHEEL_DELTA_WPARAM(wParam)  ((short)HIWORD(wParam))
#endif

int internal_route_sizeChanged(void* wParam, void* lParam);
int internal_route_touchMove(void* wParam, void* lParam);
int internal_route_touchDown(void* wParam, void* lParam);
int internal_route_touchUp(void* wParam, void* lParam);
int internal_route_touchWheel(void* wParam, void* lParam);
int internal_route_ncHitTest(void* wParam, void* lParam);

void KillGLWindow(void)								// Properly Kill The Window
{
	/*if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{}									// Set RC To NULL
	}

	if (hDC && !ReleaseDC(g_hWnd,hDC))					// Are We Able To Release The DC
	{									// Set DC To NULL
	}

	if (g_hWnd && !DestroyWindow(g_hWnd))					// Are We Able To Destroy The Window?
	{									// Set hWnd To NULL
	}

	if (!UnregisterClass("ufoApp",hInstance))			// Are We Able To Unregister Class
	{							// Set hInstance To NULL
	}*/
}

int CreateGLWindow(char* title, int width, int height, int bits, int fullscreenflag)
{	
	ufoRect rectScreen = {0, 0, width, height};
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	//fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;	// Redraw On Size, And Own DC For Window.
	if (g_appInfo.winStyle != LAYERED_WIN) {
		wc.style |= CS_OWNDC;
	}
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "ufoApp";								// Set The Class Name

	RegisterClass(&wc);
	
	switch (g_appInfo.winStyle) {
	case STANDARD_WIN:
		{
			dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
			dwStyle = WS_OVERLAPPEDWINDOW;
		}
		break;

	case POPUP_WIN:
		{
			dwExStyle= 0;
			dwStyle=WS_POPUP|WS_SYSMENU|WS_VISIBLE;
		}
		break;

	case LAYERED_WIN:
		{
			dwExStyle= 0x00080000;//WS_EX_LAYERED;
			dwStyle=WS_POPUP|WS_VISIBLE;
		}
		break;
	}

	WindowRect.left *= ufoGetDPI();
	WindowRect.top *= ufoGetDPI();
	WindowRect.right *= ufoGetDPI();
	WindowRect.bottom *= ufoGetDPI();
	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	g_hWnd=CreateWindowEx(dwExStyle,							// Extended Style For The Window
								"ufoApp",							// Class Name
								title,								// Window Title
								dwStyle,					// Required Window Style
								((GetSystemMetrics(SM_CXSCREEN))-(WindowRect.right-WindowRect.left))/2, 
								((GetSystemMetrics(SM_CYSCREEN))-(WindowRect.bottom-WindowRect.top))/2,
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL);

	//MoveWindow(g_hWnd, 100, 100, WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top, FALSE);


	ShowWindow(g_hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(g_hWnd);						// Slightly Higher Priority
	SetFocus(g_hWnd);									// Sets Keyboard Focus To The Window

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(HWND hWnd,	UINT uMsg, WPARAM wParam, LPARAM lParam)	
{
	switch (uMsg)						
	{
		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC _hdc = BeginPaint(hWnd, &ps);

			ufoAddFreshRect(0);	
			
			EndPaint(hWnd, &ps);
			break;
		}

		/*case WM_ACTIVATE:					
		{
			if (!HIWORD(wParam))					
			{
				//active=TRUE;						// Program Is Active
			}
			else
			{
				//active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}*/

		/*case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}*/

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			//keys[wParam] = TRUE;					// If So, Mark It As TRUE
			return 0;								// Jump Back
		}

		/*case WM_NCLBUTTONDOWN:
			{
				return 0;
			}*/
		case WM_LBUTTONDOWN:
			{
				ufoPoint pt = {LOWORD(lParam), HIWORD(lParam)};
				internal_route_touchDown(&pt, 0);
				SetCapture(hWnd);

				//MoveWindow(g_hWnd, 100, 100, 400, 440, FALSE);
			}
			break;

		case WM_LBUTTONUP:
			{
				ufoPoint pt = {LOWORD(lParam), HIWORD(lParam)};
				internal_route_touchUp(&pt, 0);
				ReleaseCapture();
			}
			break;

		case WM_MOUSEMOVE:
			{
				ufoPoint pt = {0};
				POINT point;
				GetCursorPos(&point);
				ScreenToClient(hWnd, &point);
				pt.x = point.x;
				pt.y = point.y;

				internal_route_touchMove(&pt, 0);	

				if (!g_bTrackMouse) {
					TRACKMOUSEEVENT csTME = {0};
					csTME.cbSize = sizeof (csTME);
					csTME.dwFlags = 0x00000001|0x00000002;//TME_LEAVE|TME_HOVER;
					csTME.hwndTrack = hWnd ;
					csTME.dwHoverTime = 10;
					g_bTrackMouse = 1;
					TrackMouseEvent(&csTME);
				}
			}
			break;

		///*
		case 0x020A://WM_MOUSEWHEEL:
			{
				ufoPoint pt = {0};
				int zDelta = GET_WHEEL_DELTA_WPARAM(wParam)/120;
				POINT point;
				GetCursorPos(&point);
				ScreenToClient(hWnd, &point);
				pt.x = point.x;
				pt.y = point.y;
				//internal_route_touchWheel(&pt, (void*)zDelta);	
			}
			break;

		case 0x02A1://WM_MOUSEHOVER:
			{
				POINT point;
				GetCursorPos(&point);
				ScreenToClient(hWnd, &point);
				if (!ufoGetTouchState()) {
					ufoPoint pt = {point.x, point.y};
					internal_route_touchMove(&pt, 0);
				}
				g_bTrackMouse = 0;
			}
			break;

		case 0x02A3://WM_MOUSELEAVE:
			{
				POINT point = {88888888, 88888888};
				ScreenToClient(hWnd, &point);
				if (1) {
					ufoPoint pt = {point.x, point.y};
					internal_route_touchMove(&pt, 0);
				}
				g_bTrackMouse = 0;
			}
			break;
			//*/

		case WM_KEYUP:								// Has A Key Been Released?
			{
			//keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}

		case WM_SIZE:
		case WM_SIZING:
			{
				RECT rc = {0};
				GetClientRect(hWnd, &rc);
				g_hWnd = hWnd;
				{
					int width = rc.right-rc.left;
					int height = rc.bottom - rc.top;
					ufoRect rectClip = {0, 0, width, height};
					internal_route_sizeChanged(&rectClip, hWnd);
					ufoRuningLoop(g_hWnd);
				}
			}
			break;

		case WM_ERASEBKGND:
			return 1;

		case WM_NCHITTEST:
			{
				int nReslut = 0;
				ufoPoint pt = {0};
				POINT point;
				GetCursorPos(&point);
				ScreenToClient(hWnd, &point);
				pt.x = point.x;
				pt.y = point.y;

				nReslut = internal_route_ncHitTest(&pt, 0);
				if (nReslut) {
					return HTCAPTION;
				}
			}
			break;
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{	
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop
	//HANDLE handle = CreateEvent(NULL, FALSE, TRUE, "ADGASDG");
	ufoSetupAppInfo(&g_appInfo); 

	if (!CreateGLWindow("ufoApp", g_appInfo.width, g_appInfo.height, 32, 0)) 
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0, PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}

		ufoRuningLoop(g_hWnd);
		//SwitchToThread();
		//MsgWaitForMultipleObjects(1, &handle, FALSE, 1, QS_ALLINPUT);
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
